//
//  QDPayManagerViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

/// 支付管理下方的广告位
final class QDPayManagerADTableViewCell :QDMetroCycleTableViewCell {
    
    override func buildView() {
        
        super.buildView()
        contentView.backgroundColor = RecordBackgroundColor
        cycleContentInsets = UIEdgeInsets(top: 25, left: 0, bottom: 0, right: 0)
        cycleView.backgroundColor = RecordBackgroundColor
        cycleView.contentView?.backgroundColor = RecordBackgroundColor
    }
    
    override func cycle(_ cycleView: RITLSDCycleScrollView, setupCustomCell cell: UICollectionViewCell & RITLSDCycleScrollViewCell, forIndex indexPath: IndexPath) {
        
        cell.imageView.backgroundColor = .white
        cell.imageView.contentMode = .scaleAspectFill
        cell.imageView.clipsToBounds = true
    }
}




/// 支付管理
final class QDPayManagerViewController: NWTableViewController,
QDLargeTitleTableHeaderScrollable,
QDPayHeaderViewDelegate,
QDPayTypeDefaultPickerViewDelegate,
SDCycleScrollViewDelegate {

    /// 支付方式选择器
    fileprivate lazy var payTypePicker: QDPayTypeDefaultPickerView = {
        
        let payTypePicker = QDPayTypeDefaultPickerView()
        payTypePicker.typeDelegate = self
        
        return payTypePicker
    }()
    
    /// 支付管理的大标题headerView
    var largeTableHeaderView : QDLargeTitleTableHeaderView {
        return headerView.largeTableHeaderView
    }
    /// 支付管理的headerView
    let headerView = QDPayHeaderView()
    /// 广告位
    fileprivate var ads = [QDAdvertisementModel]()
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
        tableView.rowHeight = QDMetroCycleTableViewCellHeight() + 5
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDPayManagerADTableViewCell.self, forCellReuseIdentifier: "ADcell")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        /// 前置颜色
        view.backgroundColor = RecordBackgroundColor
        largeTableHeaderView.backgroundColor = view.backgroundColor
        headerView.backgroundColor = view.backgroundColor
        
        // largeTitle
        largeTableHeaderView.title = "支付管理"
        headerView.delegate = self
        
        headerView.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 232 + (hasPhoneHeader() ? 20 : 0) + QDLargeTitleTableHeaderViewNormalHeight))
        
        tableView.tableHeaderView = headerView
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestPayTypes), name: QDPayTypeStatusDidChangedNotificationName, object: nibName)
        
        //请求支付方式
        requestPayTypes()
        //请求广告位
        requestAdsInPageManagerController()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setNavigationBarShadowViewHidden(navigationItem.title == nil)
    }
    
    override var tableViewBackgroundColor: UIColor { return RecordBackgroundColor }
    
    // MARK: 导航栏
    override var nav_mutableBarShadowHidden: Bool { return true }
    override var nav_barTintColor: UIColor { return RecordBackgroundColor }
    
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        tableViewDidScroll(contentOfset: scrollView.contentOffset) { (isShow) in
            setNavigationBarShadowViewHidden(!isShow)
        }
    }
    
    
    //TODO: 广告位
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ads.count == 0 ? 0 : 1
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ADcell", for: indexPath)
        
        if let adCell = cell as? QDPayManagerADTableViewCell {
            //进行赋值
            adCell.cycleView.imageURLStringsGroup = ads.map { $0.imgUrl }
            adCell.cycleView.delegate = self
        }
        
        return cell
    }
    
    
    // MARK: SDCycleScrollViewDelegate
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {

        let advertisement = ads[index]
        pushToShareWebViewController(url: advertisement.url, shareTitle: advertisement.title,title: "详情")
    }
    
}



extension QDPayManagerViewController {
    
    /// 请求广告
    func requestAdsInPageManagerController(){
        
        QDNetworkingManager.requestStaticAds(type: .pay, success: { (datas) in
            
            self.ads = datas
            self.tableView.reloadData()
            
        }, error: nil)
    }
    

    /// 请求支付方式
    @objc func requestPayTypes(){
        
        view.showWatingHUD()
        
        QDNetworkingManager.requestPayTypeList(complete: { (payTypes, isBlack, cardId) in
            
            self.view.dismissHUD()
            let defaultType = payTypes.filter { $0.defaultChannel }//获得默认的支付方式
            if defaultType.count > 0 {//表示有默认支付方式
                //更新header展示的内容
                self.headerView.typeLabel.text = "\(defaultType.first!.type.title)支付"
                QDUserInfoModel.share.currentChannel = "当前默认\(defaultType.first!.type.title)"
                
            }else {
                self.headerView.typeLabel.text = "暂时没有默认支付方式"
                //修改本地数据
                QDUserInfoModel.share.currentChannel = ""
            }
            
            //刷新
            NotificationCenter.default.post(name: QDUserInfoStatusDidChangedNotificationName, object: nil)

            //更新用户id
            self.headerView.userLabel.text = "用户ID:\(cardId)"
            
            //更新绑定新支付方式下的title
            let signTypes = payTypes.filter { $0.discount }
            if signTypes.count > 0 {
                self.headerView.newExternLabel.text = signTypes.first!.discountMsg
            }
            
            //设置支付方式
            self.payTypePicker.signPayTypes = payTypes.filter { $0.signStatusType == .binding }
            
        }) { (msg, erroType) in
            self.view.showTextHUD(text: msg)
        }
    }
}




extension QDPayHeaderViewDelegate where Self: QDPayManagerViewController {
    
    func payHeaderView(view: QDPayHeaderView,type:QDPayHeaderView.PayHeaderAction) {
        
        /// 跳转绑定新支付方式
        func pushToNewPayType(){
            router(platform: .payTypeList)
//            navigationController?.pushViewController(QDPayTypeViewController(), animated: true)
        }
    
        /// 跳出选择支付方式
        func presentSwitchPayType(){
            payTypePicker.show()
        }
        
        
        //进行界面跳转
        switch type {
            case .new: pushToNewPayType()
            case .switch: presentSwitchPayType()
        }
        
    }
}

extension QDPayTypeDefaultPickerViewDelegate where Self: QDPayManagerViewController {
    
    /// 绑定新的支付方式
    func bindingNewPayType(in view: QDPayTypeDefaultPickerView) {
        payHeaderView(view: headerView, type: QDPayHeaderView.PayHeaderAction.new)
        payTypePicker.dimissAtOnce()
    }
    
    
    /// 选择后的回调
    func payTypePickerView(view: QDPayTypeDefaultPickerView, select type: QDPayType, isCurrent: Bool,indexPath: IndexPath) {
        
        //进行请求
        if !isCurrent {
            
            self.view.showTextHUD(text: "正在设置默认支付方式")
            
            QDNetworkingManager.requestChangedDefaultChannel(channelId: /*type.rawValue*/view.signPayTypes[indexPath.row].payChannelId, complete: {
                
                self.view.dismissHUD()
                self.requestPayTypes()//刷新
                print("当前默认\(type.title)")
                QDUserInfoModel.share.currentChannel = "当前默认\(type.title)"
                
                //刷新
                NotificationCenter.default.post(name: QDUserInfoStatusDidChangedNotificationName, object: nil)
                NotificationCenter.default.post(name: QDPayTypeStatusDidChangedNotificationName, object: nil)
                
            }) { (msg, errorType) in
                
                self.view.showTextHUD(text: msg)
                
                //默认支付方式回滚
                view.resetOriginPayTypes()
            }
        }
        
        view.dismiss()
    }
}
